cc.Class({
    extends: cc.Component,

    properties: {
        ipSvr: cc.EditBox,
        gateSvrIP: null,
        gateSvrPort: null,
    },

    // use this for initialization
    onLoad: function () {
        window.ui_gate = this;
    },

    onDestroy: function () {
        pomelo.disconnect();
    },

    onClickExit: function () { },

    onClickConnect: function () {
        var svrStr = this.ipSvr.string;
        if (svrStr == null || svrStr.length == 0) {
            cc.log("svr is nil");
            return;
        }
        var strs = svrStr.split(":");

        this.gateSvrIP = strs[0];
        this.gateSvrPort = strs[1];

        this.connectGateSvr();
    },

    // 连接网关服务器，获取可用服务
    connectGateSvr: function () {
        var that = this;

        pomelo.init({ host: that.gateSvrIP, port: that.gateSvrPort, log: true },
            function () {
                pomelo.request("gate.gateHandler.queryEntry", null,
                    function (data1) {
                        cc.log("pomelo.return[gate.gateHandler.queryEntry]: data is ", data1);
                        pomelo.disconnect();
                        if (data1.code === 200) {
                            that.logicSvrIP = data1.host == "127.0.0.1" || "localhost" ? that.gateSvrIP : data1.host;
                            that.logicSvrPort = data1.port;
                            that.connectLogicSvr();
                        }
                        else {
                            // 没有可用的服务器
                        }
                    });
            });
    },

    // 连接逻辑服务器
    connectLogicSvr: function () {
        var that = this;

        pomelo.init({ host: that.logicSvrIP, port: that.logicSvrPort, log: true }, function () {
            pomelo.request("connector.entryHandler.enter", null,
                function (data1) {
                    cc.log("pomelo.return[connector.entryHandler.enter]: data is ", data1);
                    if (data1.code === 200) {
                        pomelo.on("disconnect", function (reason) {
                            cc.log("ui_gate.disconnect: ", reason);
                            uiMgr.closeAllExcept(["ui_bg", "ui_gate"], true);
                        });

                        pomelo.on("io-error", function (data) {
                            cc.log("ui_gate.io-error: ", data);
                            uiMgr.closeAllExcept(["ui_bg", "ui_gate"], true);
                        });

                        uiMgr.close("ui_gate");
                        uiMgr.open("ui_login");
                    }
                    else {
                        // 没有可用的服务器
                    }
                });
        });
    }
});
